package com.sonicboom.nurun.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.log4j.Logger;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

public class AxicomClient {
    private static final Logger logger = Logger.getLogger(AxicomClient.class);

    static {
        SSLContext ctx;
        TrustManager[] trustAllCerts = new X509TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }};
        try {
            ctx = SSLContext.getInstance("SSL");
            ctx.init(null, trustAllCerts, null);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }

        SSLContext.setDefault(ctx);

    }

    private final String sourceId;
    private final String baseUrl;

    public AxicomClient(String sourceId, String baseUrl) {
        this.sourceId = sourceId;
        this.baseUrl = baseUrl;


    }

    public static String encrypt(String strSrc) {
        final String encName = "MD5";
        MessageDigest md;
        String strDes;

        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance(encName);
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Invalid algorithm.");
            return null;
        }
        return strDes;
    }

    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    public RegisterResult register(String userName, String password, String mail) {
        Map<String, String> request = new HashMap<>();
        request.put("username", userName);
        request.put("password", encrypt(password));
        request.put("mail", mail);
        request.put("source_id", sourceId);
        String requestData = JSONSerializer.toJSON(request).toString(0);
        try {
            requestData = URLEncoder.encode(requestData, "utf-8");
        } catch (Exception e) {
            return RegisterResult.fail;
        }
        logger.info("request:" + requestData);
        ClientConfig config = new DefaultClientConfig();
        String result = Client.create(config).resource(String.format(baseUrl, "New", requestData)).get(String.class);
        logger.info("response:" + result);
        JSONObject json = (JSONObject) JSONSerializer.toJSON(result);
        JSONObject ws_response = json.getJSONObject("WS_RESPONSE");

        if (ws_response != null) {
            String return_code = ws_response.getString("RETURN_CODE");
            if (return_code != null && return_code.equals("000")) {
                return RegisterResult.success;
            } else if (return_code != null && return_code.equals("610")) {
                return RegisterResult.alreadyExist;
            }
        }

        return RegisterResult.fail;
    }

    public enum RegisterResult {
        success("成功"),
        alreadyExist("该用户名已经存在"),
        fail("注册失败");
        private final String message;

        RegisterResult(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }
    }

    public LoginResult login(String userName, String password) {
        Map<String, String> request = new HashMap<>();
        String login_type = "1";
        if (userName.indexOf("@") > 0) {
            login_type = "3";
        }
        request.put("login_name", userName);
        request.put("login_type", login_type);
        request.put("source_id", sourceId);
        String requestData = JSONSerializer.toJSON(request).toString(0);
        try {
            requestData = URLEncoder.encode(requestData, "utf-8");
        } catch (Exception e) {
            return LoginResult.fail;
        }
        logger.info("request:" + requestData);
        ClientConfig config = new DefaultClientConfig();
        String result = Client.create(config).resource(String.format(baseUrl, "login", requestData)).get(String.class);
        logger.info("response:" + result);
        JSONObject json = (JSONObject) JSONSerializer.toJSON(result);
        JSONObject ws_response = json.getJSONObject("WS_RESPONSE");

        if (ws_response != null) {
            String return_code = ws_response.getString("RETURN_CODE");
            if (return_code != null && return_code.equals("000")) {
                return LoginResult.success;
//                JSONObject customer_infos = json.getJSONObject("CUSTOMERS");
//                JSONObject customer_info = customer_infos.getJSONObject("CUSTOMER_INFO");
//                String password1 = customer_info.getString("password");
//                if (encrypt(password).equals(password1)) {
//                    return LoginResult.success;
//                } else {
//                    return LoginResult.invalidPassword;
//                }
            } else if (return_code != null && return_code.equals("611")) {
                return LoginResult.notExist;
            }
        }

        return LoginResult.fail;
    }


    public enum LoginResult {
        success("成功"),
        fail("登录失败"),
        notExist("不存在该用户"),
        invalidPassword("密码不正确");
        private final String message;

        LoginResult(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }
    }

}
